# !/user/bin/env python3
# -*- coding: utf-8 -*-
# -- anth bluedolphi ---

import hmac
import base64
import struct
import hashlib
import time
import http.client

def get_webservertime_1():
    startTime = time.time()
    time_conn=http.client.HTTPConnection('www.baidu.com')
    time_conn.request("GET", "/")
    r=time_conn.getresponse()
    #r.getheaders() #获取所有的http头
    ts=  r.getheader('date') #获取http头date部分
    #print("time",time.time())
    #将GMT时间转换成北京时间
    ltime= time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
    #print("ltime=",ltime)
    ttime=time.localtime(time.mktime(ltime)+8*60*60)
    return ttime

def get_webservertime():
    time_conn=http.client.HTTPConnection('www.baidu.com')
    time_conn.request("GET", "/")
    r=time_conn.getresponse()
    #r.getheaders() #获取所有的http头
    ts=  r.getheader('date') #获取http头date部分
    #将GMT时间转换成北京时间
    ltime= time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
    # print(ltime)
    ttime=time.localtime(time.mktime(ltime)+8*60*60)

    print(time.mktime(ttime))
    dat="%u-%02u-%02u"%(ttime.tm_year,ttime.tm_mon,ttime.tm_mday)
    tm="%02u:%02u:%02u"%(ttime.tm_hour,ttime.tm_min,ttime.tm_sec)
    currenttime=dat+" "+tm

    return currenttime

def calGoogleCode(secret_key):
    t = time.mktime(get_webservertime_1())
    duration_input = int(t)//30
    #print(duration_input)
    key = base64.b32decode(secret_key)  # Length of the key must be a multiplier of eight
    msg = struct.pack(">Q", duration_input)
    google_code = hmac.new(key, msg, hashlib.sha1).digest()
    o = google_code[19] & 15
    google_code = str((struct.unpack(">I", google_code[o:o+4])[0] & 0x7fffffff) % 1000000)
    if len(google_code) == 5:  # Only if length of the code is 5, a zero will be added at the beginning of the code.
        google_code = '0' + google_code
    return google_code



